#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QFileDialog>
#include <QFile>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    m_comtrade = nullptr;

    //通道颜色
    m_color.insert("A", Qt::yellow);
    m_color.insert("B", Qt::green);
    m_color.insert("C", Qt::red);
    m_color.insert("Z", Qt::blue);

    //禁用缩放按钮
    button_disenable();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete m_comtrade;
    m_comtrade = nullptr;
    m_cust_plot.clear();
    m_label_s.clear();
}

//选择配置文件CFG
void MainWindow::on_btn_filechoice_clicked()
{
    if(m_comtrade)
    {
        delete m_comtrade;
        m_comtrade = nullptr;
        m_cust_plot.clear();
        m_label_s.clear();
    }

    //录波文件选择
    QString filename = QFileDialog::getOpenFileName(this, QString("打开文件"), qApp->applicationDirPath(), "*.cfg");
    if(filename.isEmpty()) return;

    m_comtrade = new ComtradeRecord;
    if(!m_comtrade->parse_init(filename))
    {
        QMessageBox::warning(this, QString("警告"), QString("录波文件解析失败"));
        qDebug() << "Open Error";
        return;
    }

    ui->lineEdit_file->setText(filename);

    button_enable();

    ui->lab_name_s->setText(m_comtrade->m_station_name);
    ui->lab_id_s->setText(m_comtrade->m_rec_dev_id);
    ui->lab_ver_s->setText(m_comtrade->m_rev_year);

    ui->lab_ch_t_s->setText(QString::number(m_comtrade->m_totalChannels));
    ui->lab_ch_ana_s->setText(QString::number(m_comtrade->m_analogChannels));
    ui->lab_ch_dig_s->setText(QString::number(m_comtrade->m_digitalChannels));

    //添加曲线
    for(int i=0; i<m_comtrade->m_analogChannels; i++)
    {
        add_analogChannel_chart(i);
    }
}

//鼠标点击显示当前鼠标的坐标值
void MainWindow::plot_clicked(QMouseEvent *event)
{
    int i=0;

    foreach (QCustomPlot *plot, m_cust_plot)
    {
        double x = plot->xAxis->pixelToCoord(event->pos().x());
        int index = get_index(x);

        double y = 0;
        if(index > 0)
        {
            y = m_data[i][index];
        }
        else
        {
            x = 0;
        }

        QString msg = QString(" 通道  %1 当前时间:%2(ms), 当前值: %3").arg(plot->yAxis->label()).arg(x).arg(y);
        m_label_s[i++]->setText(msg);
    }
}

//添加一条曲线
void MainWindow::add_analogChannel_chart(int index)
{
    //获取一个通道信息
    ComtradeAnalogChannel *ana_cha = m_comtrade->m_analogc_ls[index];

    QString title = ana_cha->m_ch_id;
    QString ph = ana_cha->m_ph;
    QColor color = m_color[ph];

    float a = ana_cha->m_a;
    float b = ana_cha->m_b;

    float Timemul = m_comtrade->m_Timemult;

    int data_len = m_comtrade->m_endsamp[0];
    double samp = m_comtrade->m_samp[0];

    //X轴时间标记
    //如果频率存在
    if(m_comtrade->m_samp.count())
    {
        for(int i=0; i<data_len; i++)
        {
            double time_d = (1/samp) * i * 1000;// - m_comtrade->m_time_s.msecsTo(m_comtrade->m_time_e);
            m_timeBaseus.append(time_d);
        }
    }
    else
    {
        //频率不存在，采用DAT文件中中的时间标记
        for(int i=0; i<data_len; i++)
        {
            double time_d = m_comtrade->m_dat_ls[i]->m_timestamp*Timemul*0.001; //ms
            m_timeBaseus.append(time_d);
        }
    }

    //X轴范围
    double x_min = m_timeBaseus[0];
    double x_max = m_timeBaseus[data_len-1];

    //Y轴范围 实际值 = 点采集数据*一次系数a + 二次系数b
    double y_min = ana_cha->m_min*a+b;
    double y_max = ana_cha->m_max*a+b;

    //曲线图画布
    QCustomPlot *plot = new QCustomPlot(ui->scrollAreaWidgetContents);

    plot->setMinimumHeight(m_min_now);

    ui->gridLayout->addWidget(plot, index, 1, 1, 6);

    //画布点击事件
    connect(plot, &QCustomPlot::mousePress, this, &MainWindow::plot_clicked);

    //拖动、缩放曲线
    plot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);

    plot->setBackground(QBrush(Qt::black));
    plot->setContentsMargins(0, 0, 0, 0);

    //X轴
    plot->xAxis->setRange(x_min, x_max);
    plot->xAxis->setLabelColor(Qt::white);
    plot->xAxis->setTickPen(QPen(Qt::white));
    plot->xAxis->setSubTickPen(QPen(Qt::white));
    plot->xAxis->setTickLabelColor(Qt::white);
    plot->xAxis->setTickLabelSide(QCPAxis::LabelSide::lsInside);
    plot->xAxis->setPadding(10);
    plot->xAxis->setOffset(10);

    //YX轴
    plot->yAxis->setLabel(title);
    plot->yAxis->setRange(y_min, y_max);
    plot->yAxis->setLabelColor(color);
    plot->yAxis->setTickPen(QPen(color));
    plot->yAxis->setSubTickPen(QPen(color));
    plot->yAxis->setTickLabelColor(color);
    plot->yAxis->setTickLabelSide(QCPAxis::LabelSide::lsInside);
    plot->yAxis->ticker()->setTickCount(3);

    //Y轴，通道数据
    QVector<double> p_data;
    for(int i=0; i<data_len; i++)
    {
        int data = m_comtrade->m_dat_ls[i]->m_AI[index];
        double ps = data*a+b;
        p_data.append(ps);
    }

    //曲线
    plot->addGraph();
    plot->graph(0)->setData(m_timeBaseus, p_data);
    plot->graph(0)->setPen(QPen(color, 2));
    plot->graph(0)->rescaleAxes();

    plot->replot();

    //信息显示
    QString msg = QString(" 通道  %1, 当前时间: 0(ms), 当前值: 0").arg(title);
    QLabel *lab = new QLabel(msg, ui->scrollAreaWidgetContents);
    lab->adjustSize();
    lab->setStyleSheet(QString::fromUtf8("background-color: #000000; color: %1;").arg(color.name()));
    lab->setMinimumSize(340, 0);

    //将曲线画布和信息提示添加到布局中
    ui->gridLayout->addWidget(lab, index, 0, 1, 1);

    m_label_s.append(lab);
    m_data.append(p_data);
    m_cust_plot.append(plot);
}

int MainWindow::get_index(double data)
{
    for(int i=0; i<m_timeBaseus.count(); i++)
    {
        if(m_timeBaseus[i] >= data)
            return i;
    }
    return -1;
}

void MainWindow::button_enable()
{
    ui->btn_amp->setEnabled(true);
    ui->btn_red->setEnabled(true);
    ui->btn_reset->setEnabled(true);
    ui->btn_clear->setEnabled(true);
}

void MainWindow::button_disenable()
{
    ui->btn_amp->setEnabled(false);
    ui->btn_red->setEnabled(false);
    ui->btn_reset->setEnabled(false);
    ui->btn_clear->setEnabled(false);
}

//放大曲线
void MainWindow::on_btn_amp_clicked()
{
    foreach (QCustomPlot *plot, m_cust_plot)
    {
        m_min_now += 1;
        if(m_min_now >= 200) m_min_now = 200;
        plot->setMinimumHeight(m_min_now);
    }
    update();
}

//缩小曲线
void MainWindow::on_btn_red_clicked()
{
    foreach (QCustomPlot *plot, m_cust_plot)
    {
        m_min_now -= 1;
        if(m_min_now <= m_min_heght) m_min_now = m_min_heght;
        plot->setMinimumHeight(m_min_now);
    }
    update();
}

//重置大小
void MainWindow::on_btn_reset_clicked()
{
    foreach (QCustomPlot *plot, m_cust_plot)
    {
        m_min_now = m_min_heght;
        plot->setMinimumHeight(m_min_now);
    }
    update();
}

//清除
void MainWindow::on_btn_clear_clicked()
{
    if(m_comtrade)
    {
        ui->lineEdit_file->clear();

        button_disenable();

        ui->lab_name_s->clear();
        ui->lab_id_s->clear();
        ui->lab_ver_s->clear();

        ui->lab_ch_t_s->clear();
        ui->lab_ch_ana_s->clear();
        ui->lab_ch_dig_s->clear();

        delete m_comtrade;
        m_comtrade = nullptr;

        foreach (QCustomPlot *plot, m_cust_plot)
        {
            delete plot;
        }

        foreach (QLabel *lab, m_label_s)
        {
            delete lab;
        }

        m_cust_plot.clear();
        m_timeBaseus.clear();
        m_data.clear();
        m_label_s.clear();
    }
}
